<template>
  <div class="com-container">
    <div class="com-chart" ref="hot_ref"></div>
    <span class="iconfont arr-left" @click="toLeft" :style="comStyle">&#xe6ef;</span>
    <span class="iconfont arr-right" @click="toRight" :style="comStyle">&#xe6ed;</span>
    <span class="cat-name" :style="comStyle">{{ catName }}</span>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import { getThemeValue } from '@/utils/theme_utils'
export default {
  data() {
    return {
      chartInstance: null,
      allData: null, // 服务器返回的数据
      currentIndex: 0, //当前所展示一级分类数据
      titleFontSize: 0
    };
  },
  created() {
    this.$socket.registerCallBack("hotData", this.getData)
  },
  mounted() {
    this.initChart();
    // this.getData();
    this.$socket.send({
      action: 'getData',
      socketType: 'hotData',
      chartName: 'hot',
      value: ''
    });
    window.addEventListener("resize", this.sceenAdapter);
    this.sceenAdapter();
  },
  destroyed() {
    window.removeEventListener("resize", this.sceenAdapter);
    clearInterval(this.timeId);
     this.$socket.unRegisterCallBack("hotData")
  },
  computed: {
    catName() {
      if (!this.allData) {
        return "";
      } else {
        return this.allData[this.currentIndex].name;
      }
    },
    comStyle() {
        return {
            fontSize: this.titleFontSize + 'px',
            color: getThemeValue(this.theme).titleColor
        }
    },
    ...mapState(['theme'])
  },
  methods: {
    //初始化echartInstance对象
    async initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.hot_ref, this.theme);
      //对图表初始化配置的控制
      const initOption = {
        title: {
          text: "热销商品销售金额占比统计",
          left: 20,
          top: 20,
        },
        legend: {
            top: '15%',
            icon: 'circle'
        },
        tooltip: {
            show: true,
            formatter: arg => {
                const thirdCategory = arg.data.children
                let total = 0
                thirdCategory.forEach(item => {
                    total += item.value
                })
                let retStr = ''
                thirdCategory.forEach(item => {
                    retStr += `
                    ${item.name}: ${parseInt(item.value /  total * 100) + '%'}
                    <br/> 
                    `
                })
                return retStr
            }
        },
        series: [
          {
            type: "pie",
            label: {
                show: false
            },
            emphasis: {
                label: {
                    show: true
                },
                labelLine: {
                    show: false
                }
            }
          },
        ],
      };
      this.chartInstance.setOption(initOption);
    },
    // 获取服务器的数据
    async getData(res) {
      // const { data: res } = await this.$http.get("hotproduct");
      // console.log(res);
      this.allData = res;
      this.updateChart();
    },
    // 更新图表
    updateChart() {
      //处理数据
      const legendData = this.allData[this.currentIndex].children.map(
        (item) => {
          return item.name;
        }
      );
      const seriesData = this.allData[this.currentIndex].children.map(
        (item) => {
          return {
            name: item.name,
            value: item.value,
            children: item.children
          };
        }
      );
      const dataOption = {
        legend: {
          data: legendData,
        },
        series: [
          {
            data: seriesData,
          },
        ],
      };
      this.chartInstance.setOption(dataOption);
    },
    //适应屏幕大小
    sceenAdapter() {
        this.titleFontSize = (this.$refs.hot_ref.offsetWidth / 100) * 3.6;
      //和分辨率相关的文字大小
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: this.titleFontSize,
          },
        },
        legend: {
            itemWidth: this.titleFontSize ,
            itemHeight: this.titleFontSize ,
            itemGap: this.titleFontSize ,
            textStyle: {
                foneSize: this.titleFontSize /  2
            }
        },
        series: [
          {
            radius: this.titleFontSize * 4.5,
            center: ['50%', '60%']
          },
        ],
      };
      this.chartInstance.setOption(adapterOption);

      this.chartInstance.resize();
    },
    toLeft() {
      this.currentIndex--;
      if (this.currentIndex < 0) {
        this.currentIndex = this.allData.length - 1;
      }
      this.updateChart();
    },
    toRight() {
      this.currentIndex++;
      if (this.currentIndex > this.allData.length - 1) {
        this.currentIndex = 0;
      }
      this.updateChart();
    },
  },
  watch: {
    theme() {
      // console.log('主题切换');
      this.chartInstance.dispose() //销毁当前的图表
      this.initChart()
      this.sceenAdapter()
      this.updateChart()

    }
  }
};
</script>

<style lang='less' scoped>
.arr-left {
  position: absolute;
  top: 50%;
  left: 10%;
  transform: translateY(-50%);
  font-size: 20px;
  color: #fff;
  cursor: pointer;
}
.arr-right {
  position: absolute;
  top: 50%;
  right: 10%;
  transform: translateY(-50%);
  font-size: 20px;
  color: #fff;
  cursor: pointer;
}
.cat-name {
  position: absolute;
  left: 80%;
  bottom: 20px;
  color: #fff;
}
</style>